package com.lanchewuyou.user.driver.lipeiui;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.MaterialDialog;
import com.lanchewuyou.user.driver.R;
import com.lanchewuyou.user.driver.bean.Company;
import com.lanchewuyou.user.driver.bean.CompanyDB;
import com.lanchewuyou.user.driver.modul.Config;
import com.lanchewuyou.user.driver.modul.OkHttpClientManager;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.squareup.okhttp.Request;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * 收集车主信息，投保公司，付费状态界面
 */
public class CustomerInforActivity extends AppCompatActivity {
    private MaterialEditText customName;
    private MaterialEditText customPhone;
    private Toolbar mToolbar;
    private Button customInforNextBtn, chooseCompany;
    private CheckBox isPay;
    private TextView payType;
    private TextView companyName;
    private CompanyDB companyDB;
    private String insureId;
    public static CustomerInforActivity instance;
    private ProgressDialog progressDialog, progressUploadDialog;
    private static String DRIVERID;
    private Toast toast = null;

    private void showTextToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(CustomerInforActivity.this, msg, Toast.LENGTH_SHORT);
        } else {
            toast.setText(msg);
        }
        toast.show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_infor);
        initViews();
        SharedPreferences sharedPreferences = getSharedPreferences(Config.PASSWORD_PATH, Activity.MODE_PRIVATE);
        DRIVERID = sharedPreferences.getString("driverid", "");
        progressDialog.show();
        instance = this;
        OkHttpClientManager.getAsyn(Config.DRIVERORDERDETAIL + "&driverid=" + DRIVERID + "&orderid=" + PickCarActivity.orderId, new OkHttpClientManager.StringCallback() {
            @Override
            public void onFailure(Request request, IOException e) {
                showTextToast("没有获取到详情");
                progressDialog.dismiss();
            }

            @Override
            public void onResponse(String response) {
                Log.d("Pickcar", response);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String status = jsonObject.getString("status");
                    if (status.equals("1")) {
                        JSONObject info = jsonObject.getJSONObject("info");
                        customName.setText(info.getString("username"));
                        customPhone.setText(info.getString("mobile"));
                        insureId = info.getJSONObject("insuranceiinfo").getString("id");
                        companyName.setText(info.getJSONObject("insuranceiinfo").getString("name"));
                        String paid = info.getString("paid");
                        if (paid.equals("0")) {
                            payType.setText("线下付款");
                            isPay.setVisibility(View.GONE);
                        } else if (paid.equals("1")) {
                            payType.setText("已收费");
                        }
                        progressDialog.dismiss();
                    } else {
                        progressDialog.dismiss();
                        showTextToast("没有获取到详情");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    progressDialog.dismiss();
                }
            }
        });
    }

    private void initViews() {
        mToolbar = (Toolbar) findViewById(R.id.custom_infor_toolbar);
        mToolbar.setTitle("基本信息采取");
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        progressDialog = new ProgressDialog(this);
        progressDialog.setTitle("载入中");
        progressDialog.setMessage("请稍等");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressDialog.setCancelable(true);
        progressUploadDialog = new ProgressDialog(this);
        progressUploadDialog.setTitle("上传中");
        progressUploadDialog.setMessage("请稍等");
        progressUploadDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        progressUploadDialog.setCancelable(true);
        customName = (MaterialEditText) findViewById(R.id.customer_name);
        customPhone = (MaterialEditText) findViewById(R.id.customer_phone);
        companyName = (TextView) findViewById(R.id.company_name);
        customInforNextBtn = (Button) findViewById(R.id.customer_infor_next_btn);
        customInforNextBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                progressUploadDialog.show();
                if (customName.getText().toString().length() != 0 && customPhone.getText().toString().length() != 0
                        && companyName.getText().length() != 0) {
                    OkHttpClientManager.getAsyn(Config.CUSTOMINFOR + PickCarActivity.orderId + "&username=" + customName.getText().toString() +
                            "&mobile=" + customPhone.getText().toString() + "&insurancei=" + insureId, new OkHttpClientManager.StringCallback() {
                        @Override
                        public void onFailure(Request request, IOException e) {
                            showTextToast("服务器提了个问题");
                            progressUploadDialog.dismiss();
                        }

                        @Override
                        public void onResponse(String response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response);
                                String status = jsonObject.getString("status");
                                if (status.equals("1")) {
                                    Intent intent1 = new Intent(CustomerInforActivity.this, CarInforActivity.class);
                                    startActivity(intent1);
                                    progressUploadDialog.dismiss();
                                } else {
                                    progressUploadDialog.dismiss();
                                    showTextToast("请求失败");
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                progressUploadDialog.dismiss();
                            }
                        }
                    });
                } else {
                    showTextToast("有信息未录入");
                    if (progressDialog.isShowing()) {
                        progressUploadDialog.dismiss();
                    }

                }
            }
        });
        companyDB = CompanyDB.getInstance(this);
        List<Company> companies = companyDB.findCompanys();
        final List<String> list = new ArrayList<>();
        for (int i = 0; i < companies.size(); i++) {
            Company company = companies.get(i);
            list.add(company.getName());
        }
        final String[] strings = list.toArray(new String[list.size()]);
        chooseCompany = (Button) findViewById(R.id.choose_company);
        chooseCompany.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new MaterialDialog.Builder(CustomerInforActivity.this)
                        .title("选择投保公司")
                        .items(strings)
                        .itemsCallback(new MaterialDialog.ListCallback() {
                            @Override
                            public void onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                                companyName.setText(text);
                                insureId = (which + 1) + "";
                            }
                        })
                        .positiveText(android.R.string.cancel)
                        .show();
            }
        });
        isPay = (CheckBox) findViewById(R.id.pay_checked);
        payType = (TextView) findViewById(R.id.pay_type);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_custom_infor, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == android.R.id.home) {
            showBackDialog();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onBackPressed() {
        showBackDialog();
    }

    private void showBackDialog() {
        new MaterialDialog.Builder(this)
                .title("退出任务")
                .content("点击确定将退出您正在执行的任务。")
                .positiveText("确定")
                .negativeText("取消")
                .callback(new MaterialDialog.ButtonCallback() {
                    @Override
                    public void onPositive(MaterialDialog dialog) {
                        finish();
                    }

                    @Override
                    public void onNegative(MaterialDialog dialog) {
                        super.onNegative(dialog);
                    }
                })
                .show();
    }
}
